﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using CommonTagTime;
using System.IO;
using System.Drawing;
using System.Web.UI.HtmlControls;
public partial class admin_TipNewsListDetail : SitePage
{
    #region Fields
    public string Command
    {

        get
        {
            object o = ViewState["Command"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["Command"] = value; }

    }
    public string ThumImage
    {

        get
        {
            object o = ViewState["ThumImage"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["ThumImage"] = value; }

    }
    public int Type
    {

        get
        {
            object o = ViewState["Type"];
            if (o != null) return (int)o;
            return int.MinValue;
        }

        set { ViewState["Type"] = value; }

    }
    #endregion

    #region Init,Load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            LoadData();
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        InitData();
    }
    protected override void OnInitComplete(EventArgs e)
    {
        base.OnInitComplete(e);

    }
    #endregion

    #region Methods
    private void LoadData()
    {
        if (this.Command == "edit")
        {
            int tipID = clsQueryString.GetInt("id");
            busTipNews objBus = new busTipNews();
            TipNews objTipNews = objBus.GetByID(tipID);
            if (objTipNews != null)
            {
                txtTitle.Text = objTipNews.Title.Trim();
                txtShortDescription.Text = objTipNews.ShortDescription.Trim();
                txtDescription.Text = objTipNews.Description.Trim();
                txtPageTitle.Text = objTipNews.PageTitle;
                txtMetaKeywords.Text = objTipNews.MetaKeywords;
                txtMetaDescription.Text = objTipNews.MetaDescription;
                if (objTipNews.IsActive)
                    chkIsActive.Checked = true;
                else chkIsActive.Checked = false;
                this.ThumImage = objTipNews.ThumbImage;
                BindImage(trThumbImage, imgThumbImage, lbtnDeleteThumbImage, objTipNews.ThumbImage);
            }
        }
    }
    private void InitData()
    {
        string validateGroup = "tipDetail";
        vsumTipNew.ValidationGroup = btnSave.ValidationGroup = reqTitle.ValidationGroup = cusThumbImage.ValidationGroup =reqShortDescription.ValidationGroup=validateGroup;
        //Init message
        reqTitle.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Title");
        reqShortDescription.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Short Description");       
        cusThumbImage.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Thumb image");
        this.Command = clsQueryString.GetString("act");
        this.Type = clsQueryString.GetInt("F_Type");
        if (this.Type != (int)enmTipNewsType.Tip && this.Type != (int)enmTipNewsType.NewEvent)
            this.Type = (int)enmTipNewsType.NewEvent;
        if (this.Type == (int)enmTipNewsType.NewEvent)
        {
            lblShortDes.Text += "(<span class='commentRequireInputText'>*</span>):";            
            reqShortDescription.Visible = true;          
        }
        else
        {
            lblShortDes.Text += ":";
            reqShortDescription.Visible = false;           
        }
    }

    private void UpdateTipNews(TipNews objTipNews)
    {
        busTipNews objBus = new busTipNews();
        objTipNews.TipNewsID = clsQueryString.GetInt("id");
        if (objBus.Update(objTipNews))
            Response.Redirect("TipNewsList.aspx?" + this.GetPageQuery);
        else lblErrorMessage.Text = Resources.Resource.MSG_UPDATE_ERROR;
    }

    private void InsertTipNews(TipNews objTipNews)
    {
        busTipNews objBus = new busTipNews();
        if (objBus.Insert(objTipNews))
            Response.Redirect("TipNewsList.aspx?" + this.GetPageQuery);
        else
        {
            this.DeleteImage(objTipNews.ThumbImage);
            lblErrorMessage.Text = Resources.Resource.MSG_INSERT_ERROR;
        }
    }
    #endregion

    #region Events

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //get datavalue
            TipNews objData = new TipNews();
            objData.CreatedBy = this.userloginName;
            objData.CreatedDate = clsDateTime.Now;
            objData.Description = txtDescription.Text.Trim();
            objData.Title = txtTitle.Text.Trim();
            objData.ShortDescription = txtShortDescription.Text.Trim();
            objData.Type = this.Type.ToString();
            objData.ThumbImage = UploadThumImage(fulThumbImage, this.ThumImage);
            objData.PageTitle = txtPageTitle.Text;
            objData.MetaKeywords = txtMetaKeywords.Text;
            objData.MetaDescription = txtMetaDescription.Text;
            if (chkIsActive.Checked)
                objData.IsActive = true;
            else
                objData.IsActive = false;
            objData.UpdatedBy = this.userloginName;
            objData.UpdatedDate = clsDateTime.Now;
            if (this.Command == "edit")
                UpdateTipNews(objData);
            else
                InsertTipNews(objData);
        }
        else
        {
            vsumTipNew.ShowMessageBox = false;
            vsumTipNew.ShowSummary = true;
        }
    }

    private string UploadThumImage(FileUpload _ful, string _oldImage)
    {
        string result = _oldImage;
        if (_ful.HasFile)
        {
            string fileNameUpload = _ful.FileName;
            string extFile = System.IO.Path.GetExtension(fileNameUpload).ToLower();
            string fileName = Guid.NewGuid().ToString();
            result = fileName + extFile;
            string fullPath = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_TIPNEW_FOLDER);
            string pathThumb = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_TIPNEW_THUMBIMAGE_FOLDER);
            if (!string.IsNullOrEmpty(_oldImage))
            {
                this.DeleteImage(_oldImage);
            }
            fullPath += fileName + extFile;
            pathThumb += fileName + extFile;
            _ful.SaveAs(fullPath);
            //Redrawimage
            int w = 142;
            if (this.Type == (int)enmTipNewsType.NewEvent)
                w = 100;
            Bitmap bmp = (Bitmap)Bitmap.FromFile(fullPath);

            if (!clsImage.RewriteImage(bmp, w, 0, pathThumb))
                _ful.SaveAs(pathThumb);
            bmp.Dispose();
            // delete source image
            clsFile.DeleteFile(fullPath);


        }
        return result;
    }
    private void DeleteImage(string _orgImageFileName)
    {
        string path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_TIPNEW_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_TIPNEW_THUMBIMAGE_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);

    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TipNewsList.aspx?" + this.GetPageQuery);
    }
    protected void lbtnDeleteThumbImage_Click(object sender, EventArgs e)
    {
        int tipID = clsQueryString.GetInt("id");
        //Step 1: Delete Image InDB
        busTipNews objBus = new busTipNews();
        TipNews objTip = objBus.GetByID(tipID);
        if (objTip != null)
        {
            objTip.ThumbImage = string.Empty;
            if (objBus.Update(objTip))
            {
                DeleteImage(this.ThumImage);
                Response.Redirect("TipNewsDetail.aspx?" + this.GetPageQuery);
            }
        }
    }
    private void BindImage(HtmlTableRow trImage, System.Web.UI.WebControls.Image img, LinkButton lbtnDelete, string value)
    {
        string imagePage = "~/" + clsConfigData.DEFAULT_UPLOAD_TIPNEW_THUMBIMAGE_FOLDER + value;
        if (File.Exists(this.Page.Server.MapPath(imagePage)))
        {
            img.ImageUrl = imagePage;
            lbtnDelete.Visible = true;
            trImage.Visible = true;
        }
        else trImage.Visible = false;
    }
    #endregion

    #region Validate Data
    protected void CheckSImageValid(object source, ServerValidateEventArgs args)
    {
        args.IsValid = clsImage.IsValidImage();
    }
    #endregion
}